<route lang="jsonc" type="home">{
    "layout": "default",
    "style": {
        "navigationStyle": "custom",
        "navigationBarTitleText": "登录"
    }
}</route>

<script lang="ts" setup>
import { onBeforeUnmount, ref } from 'vue'
import { getLoginPass, getLoginY, getLoginYM } from '@/api/login/login'
import { useRouter } from '@/hooks/useRouter'
import { useStorage } from '@/hooks/useStorage'
import { useToast } from '@/hooks/useToast'

const { push } = useRouter()
const { showToast } = useToast()
const { setStorage } = useStorage()

// 响应式数据
const loginType = ref<'sms' | 'pwd'>('sms')//登录类型
const showPwd = ref(false) //是否显示密码
const isAgree = ref(false) //是否同意协议
const countDown = ref(0) //验证码的倒计时
const mobile = ref('') //手机号
const password = ref('') //密码
const smsCode = ref('') //验证码

// 定时器
let countDownTimer: number | null = null

// 返回上一页
function handleClickLeft() {
    uni.navigateBack()
}

// 切换登录方式
const switchLoginType: (type: 'sms' | 'pwd') => void = (type) => {
    loginType.value = type
}

// 切换密码显示状态
const togglePwd: () => void = () => {
    showPwd.value = !showPwd.value
}

// 发送验证码
const sendSms: () => Promise<void> = async () => {
    if (countDown.value > 0)
        return

    if (!mobile.value || mobile.value.length !== 11) {
        showToast('请输入正确的手机号')
        return
    }

    try {
        const res = await getLoginY({
            type: 'login',
            mobile: mobile.value,
        })

        if (res.code === 10000) {
            console.log('收到的验证码:', res.data.code)
            showToast('验证码已发送')
            // 开始倒计时
            countDown.value = 60
            countDownTimer = setInterval(() => {
                countDown.value--
                if (countDown.value <= 0 && countDownTimer) {
                    clearInterval(countDownTimer)
                    countDownTimer = null
                }
            }, 1000)
        }
        else {
            showToast(res.message || '验证码发送失败')
        }
    }
    catch (error) {
        showToast('验证码发送失败')
        console.error('发送验证码错误:', error)
    }
}


// 验证码登录
const phoneLogin: () => Promise<void> = async () => {
    if (!isAgree.value) {
        showToast('请先同意协议')
        return
    }
    if (!mobile.value || mobile.value.length !== 11) {
        showToast('请输入正确的手机号')
        return
    }
    if (!smsCode.value || smsCode.value.length !== 6) {
        showToast('请输入6位验证码')
        return
    }

    try {
        const res = await getLoginYM({
            mobile: mobile.value,
            code: smsCode.value,
        })

        console.log(res)

        if (res.code === 10000) {
            handleLoginSuccess(res.data)
        }
        else {
            showToast(res.message || '登录失败，请检查验证码')
        }
    }
    catch (error) {
        showToast('网络请求失败')
        console.error('验证码登录错误:', error)
    }
}

// 密码登录
const handleLogin: () => Promise<void> = async () => {
    if (!isAgree.value) {
        showToast('请先同意协议')
        return
    }
    if (!mobile.value) {
        showToast('请输入手机号')
        return
    }
    if (!password.value) {
        showToast('请输入密码')
        return
    }

    try {
        const res = await getLoginPass({
            mobile: mobile.value,
            password: password.value,
        })

        if (res.code === 10000) {
            handleLoginSuccess(res.data)
        }
        else {
            showToast(res.message || '登录失败，请检查账号密码')
        }
    }
    catch (error) {
        showToast('网络请求失败')
        console.error('密码登录错误:', error)
    }
}

// 定义用户数据类型
interface UserAuthData {
    token: string
    refreshToken: string
    avatar: string
    mobile: string
    account: string
    id: string
}

// 登录成功处理
const handleLoginSuccess: (data: UserAuthData) => void = (data) => {
    showToast('登录成功', 'success')
    // 存储token和用户信息
    setStorage('token', data.token)
    setStorage('refreshToken', data.refreshToken)
    setStorage('userInfo', {
        avatar: data.avatar,
        mobile: data.mobile,
        account: data.account,
        id: data.id,
    })
    // 跳转到首页
    push('/pages/index/index', { type: 'switchTab' })
}

// 切换协议勾选状态
const toggleAgree: () => void = () => {
    isAgree.value = !isAgree.value
}

// 跳转到手机绑定页面
const goToBindPhone: () => void = () => {
    push('/pages/bindPhone/bindPhone')
}
// 清除定时器
onBeforeUnmount(() => {
    if (countDownTimer) {
        clearInterval(countDownTimer)
    }
})
</script>

<template>
    <!-- 导航栏 -->
    <wd-navbar left-arrow :bordered="false" class="login-navbar" @click-left="handleClickLeft">
        <template #right>
            <navigator url="/pages/login/register/register" open-type="navigate" hover-class="navigator-hover">
                <view style="color: #31c9ad;">
                    注册
                </view>
            </navigator>
        </template>
    </wd-navbar>

    <view class="login-container">
        <!-- 登录方式标题 + 切换 -->
        <view class="title-wrap">
            <view v-if="loginType === 'sms'" class="title-wrap">
                <view style="font-size: 48rpx;font-weight: 500;">
                    手机验证码登录
                </view>
                <view @tap="() => switchLoginType('pwd')">
                    <text style="font-size: 30rpx;">密码登录</text>
                    <image style="width: 25rpx;height: 25rpx;" src="/static/images/right.png" />
                </view>
            </view>
            <view v-else class="title-wrap">
                <view style="font-size: 48rpx;font-weight: 500;">
                    密码登录
                </view>
                <view @tap="() => switchLoginType('sms')">
                    <text style="font-size: 30rpx;">手机验证码登录</text>
                    <image style="width: 25rpx;height: 25rpx;" src="/static/images/right.png" />
                </view>
            </view>
        </view>

        <!-- 手机验证码登录表单 -->
        <view v-if="loginType === 'sms'" class="form sms-form">
            <!-- 手机号输入框 -->
            <input v-model="mobile" class="input" placeholder="请输入手机号码" type="number">

            <!-- 验证码输入区 -->
            <view class="sms-row">
                <input v-model="smsCode" class="input" placeholder="请输入短信验证码" type="number">
                <text class="send-sms" :class="{ 'count-down': countDown > 0 }" @tap="sendSms">
                    {{ countDown > 0 ? `${countDown}s后重新获取` : '获取验证码' }}
                </text>
            </view>

            <!-- 协议勾选 -->
            <checkbox-group class="agreement-group">
                <label class="agreement-label">
                    <checkbox class="agreement-checkbox" @tap="toggleAgree" />
                    <text>我已同意</text>
                    <navigator url="/pages/userAgreement/userAgreement" class="protocol">用户协议</navigator>
                    <text>及</text>
                    <navigator url="/pages/agreement/privacyPolicy" class="protocol">隐私协议</navigator>
                </label>
            </checkbox-group>

            <!-- 登录按钮 -->
            <button class="login-btn" :disabled="!isAgree || !mobile || !smsCode" @tap="phoneLogin">
                登录
            </button>
        </view>

        <!-- 密码登录表单 -->
        <view v-else class="form pwd-form">
            <input v-model="mobile" class="input" placeholder="请输入手机号码" type="number">
            <input v-model="password" class="input" placeholder="请输入密码" :type="showPwd ? 'text' : 'password'">
            <text class="eye-icon" @tap="togglePwd">
                {{ showPwd ? '隐藏' : '显示' }}
            </text>

            <checkbox-group class="agreement-group">
                <label class="agreement-label">
                    <checkbox class="agreement-checkbox" @tap="toggleAgree" />
                    <text>我已同意</text>
                    <navigator url="/pages/userAgreement/userAgreement" class="protocol">用户协议</navigator>
                    <text>及</text>
                    <navigator url="/pages/agreement/privacyPolicy" class="protocol">隐私协议</navigator>
                </label>
            </checkbox-group>

            <button class="login-btn" :disabled="!isAgree || !mobile || !password" @tap="handleLogin">
                登录
            </button>

            <navigator url="/pages/forgetPwd/forgetPwd" class="forget-pwd">
                忘记密码?
            </navigator>
        </view>

        <!-- 第三方登录 -->
        <view class="third-party">
            <text class="third-title">————— 第三方登录 —————</text>
            <view>
                <image class="third-icon" src="/static/images/QQ.png" @tap="goToBindPhone" />
            </view>
        </view>
    </view>
</template>

<style lang="scss" scoped>
.login-navbar {
    width: 750rpx;
    height: 88rpx;
}

.login-container {
    padding: 30rpx;
}

.title-wrap {
    display: flex;
    width: 100%;
    justify-content: space-between;
    margin-bottom: 40rpx;
}

.form {
    display: flex;
    flex-direction: column;
    gap: 24rpx;
    margin-top: 50rpx;
}

.input {
    height: 103rpx;
    line-height: 80rpx;
    padding: 0 24rpx;
    border-bottom: 2rpx solid #eee;
    border-radius: 12rpx;
    font-size: 28rpx;
    color: #333;
}

.sms-row {
    display: flex;
    align-items: center;
    gap: 20rpx;
}

.send-sms {
    color: #16c2a3;
    font-size: 26rpx;
    padding: 0 24rpx;
    white-space: nowrap;
}

.count-down {
    color: #999;
    pointer-events: none;
}

.eye-icon {
    color: #16c2a3;
    font-size: 26rpx;
    text-align: right;
    margin-top: -85rpx;
    margin-right: 16rpx;
}

.agreement-group {
    font-size: 26rpx;
    color: #999;
    margin: 30rpx 0;
}

.agreement-label {
    display: flex;
    align-items: center;
}

.agreement-checkbox {
    transform: scale(0.6);
    margin-right: 12rpx;
}

.protocol {
    color: #30c9ad;
    text-decoration: none;
    margin: 0 8rpx;
}

.login-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background-color: #16c2a3;
    color: #fff;
    font-size: 32rpx;
    border-radius: 50rpx;
    margin-top: 20rpx;

    &[disabled] {
        background-color: #f5f5f5;
        color: #ccc;
    }
}

.forget-pwd {
    text-align: center;
    color: #999;
    font-size: 28rpx;
    margin-top: 20rpx;
}

.third-party {
    text-align: center;
    margin-top: 290rpx;

    .third-title {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 40rpx;
    }

    .third-icon {
        margin-top: 30rpx;
        width: 60rpx;
        height: 60rpx;
    }
}
</style>
